package service

import (
	"fmt"
	"io"
	"math/rand"
	"net/http"
	"os"
	"strings"
	"time"
)

//接受图片 ---> 发送图片路径
func Upload(rep *http.Request) (string,error){
	//获取图片消息 ---> 图片参数名称：file
	srcFile,head,err := rep.FormFile("file")
	if err != nil{
		return "",err
	}
	//默认为png ---> 获取文件的类别
	suffix := ".png"
	ofilName := head.Filename
	tem := strings.Split(ofilName,".")
	if len(tem) > 1{
		suffix = "." + tem[len(tem)-1]
	}
	fileName := fmt.Sprintf("%d%04d%s",time.Now().Unix(),rand.Int31(),suffix)
	dstFile,err  := os.Create("picture/upload/"+fileName)
	if err != nil{
		return "",nil
	}
	_,err = io.Copy(dstFile,srcFile)
	if err != nil{
		return "",nil
	}
	url := "./picture/upload/" + fileName
	return url,nil
}
